import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/login/model/login_resp.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/startup/env/env.dart';
import 'package:tracker/utils/toast_utils.dart';

class HttpInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 请求头加上微信小程序的appid
    options.headers['APPID'] = Env.envConfig.wxAppId;
    options.headers['APP-VERSION'] = Env.envConfig.appVersion;
    options.headers['APP-VERSION-CODE'] = Env.envConfig.buildNumber;
    options.headers['API-VERSION'] = 1;
    options.headers['PLATFORM'] = Platform.isIOS ? 'ios' : 'android';
    // 请求头加上token
    LoginData loginData = SpUtil.getObj('loginData', (v) => LoginData().fromJson(v), defValue: LoginData());
    if (loginData.token != null) {
      options.headers['satoken'] = loginData.token;
    }

    return handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // XLogger.info('response: ${response.data}');
    if (response.data['code'] == 403) {
      XLogger.info('token过期');
      // token过期
      // ToastUtils.showToast('登录过期，请重新登录');
      // 清除token
      SpUtil.putBool('isLogin', false);
      SpUtil.remove('loginData');
      // 跳转到登录页
      // XLogger.info('跳转到登录页-start');
      // GlobalContext.getContext().replace('/login');
      // XLogger.info('跳转到登录页-end');
      throw DioException(
          requestOptions: response.requestOptions, response: response, type: DioExceptionType.badCertificate);

      // handler.reject(DioException(requestOptions: response.requestOptions, response: response, type: DioExceptionType.badCertificate));
    } else {
      handler.next(response);
    }
  }

  /// 请求异常处理
  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    XLogger.error('请求异常：${err.type}');
    XLogger.error('请求异常：${err.response}');

    switch (err.type) {
      case DioExceptionType.connectionTimeout:
        ToastUtils.showToast('网络连接超时，请检查网络设置');
        break;
      case DioExceptionType.sendTimeout:
        ToastUtils.showToast('网络连接超时，请检查网络设置');
        break;
      case DioExceptionType.receiveTimeout:
        ToastUtils.showToast('服务器异常，请稍后重试！');
        break;
      case DioExceptionType.cancel:
        ToastUtils.showToast('请求已被取消');
        break;
      case DioExceptionType.unknown:
        ToastUtils.showToast('网络异常，请稍后重试！');
        break;
      case DioExceptionType.badCertificate:
        ToastUtils.showToast('登录过期，请重新登录');
        try {
          RouterManager.routerConfig.go('/login');
        } catch (e) {
          XLogger.error('跳转到登录页失败');
          // 打印错误信息
          XLogger.error(e);
        }
        break;
      case DioExceptionType.badResponse:
        ToastUtils.showToast('网络异常，请稍后重试！');
        break;
      default:
        ToastUtils.showToast('网络异常，请稍后重试！');
        break;
    }
    return handler.next(err);
  }
}
